package jp.eisbahn.eclipse.plugins.twitterclipse.internal;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import jp.eisbahn.eclipse.plugins.twitterclipse.HttpRequestTimeoutException;
import jp.eisbahn.eclipse.plugins.twitterclipse.TwitterStatus;
import net.sf.json.JSONArray;

import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;

class TwitterStatusObserver implements Runnable {
	
	private TwitterclipseEngine engine;
	
	private boolean finish;
	
	private Date lastObservedDate;
	
	TwitterStatusObserver(TwitterclipseEngine engine) {
		super();
		this.engine = engine;
		finish = false;
		lastObservedDate = null;
	}
	
	void finish() {
		finish = true;
	}

	public void run() {
		System.out.println("Start a observer of twitter status.");
		TwitterclipsePlugin plugin = TwitterclipsePlugin.getDefault();
		TwitterclipseConfig config = plugin.getTwitterclipseConfiguration();
		int cnt = config.getStatusObserveSpan();
		while(!finish) {
			int observeSpan = config.getStatusObserveSpan();
			if (cnt >= observeSpan) {
				try {
					List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
					if (lastObservedDate != null) {
						DateFormat format = new SimpleDateFormat("EEE MMM d HH:mm:ss Z yyyy", Locale.US);
						String since = format.format(lastObservedDate);
						nameValuePairs.add(new NameValuePair("since", since));
					}
					GetMethod method = HttpClientUtils.createGetMethod(
							"/statuses/friends_timeline.json", nameValuePairs.toArray(new NameValuePair[0]));
//							"/statuses/user_timeline.json", nameValuePairs.toArray(new NameValuePair[0]));
					JSONArray json = (JSONArray)HttpClientUtils.executeMethod(method, 60, true);
					List<TwitterStatus> statusList = ResponseParserUtils.parseStatusesFriendsTimelineResponse(json);
					engine.newStatusListReceived(statusList);
					lastObservedDate = new Date();
					cnt = -1;
				} catch(IOException e) {
					e.printStackTrace();
					engine.handleException(e);
					cnt = -1;
				} catch (HttpRequestFailureException e) {
					int status = e.getStatus();
					if (status != HttpStatus.SC_NOT_MODIFIED) {
						e.printStackTrace();
						engine.handleException(e);
					} else {
						engine.statusNotModified();
					}
					cnt = -1;
				} catch (HttpRequestTimeoutException e) {
					e.printStackTrace();
					engine.handleException(e);
					cnt = -1;
				} catch (Exception e) {
					e.printStackTrace();
					engine.handleException(e);
					cnt = -1;
				}
			}
			try {
				Thread.sleep(1000);
			} catch(InterruptedException e) {
			}
			cnt++;
		}
		System.out.println("Finish a observer of twitter status.");
	}

}
